﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
using System.Resources;
using System.Collections;

namespace CodeIn.Utils {
	/// <summary>
	/// A collection of static methods used to manipulate an assembly and its resources.
	/// </summary>
	public class AssemblyUtils {
		/// <summary>
		/// Returns a dictionary of the assembly resources (not embedded).
		/// </summary>
		/// <param name="filter">A regex filter for the resource paths.</param>
		public static IDictionary<string, UnmanagedMemoryStream> GetResources(string filter) {
			var asm = Assembly.GetEntryAssembly();
			string resName = asm.GetName().Name + ".g.resources";
			Stream manifestStream = asm.GetManifestResourceStream(resName);
			ResourceReader reader = new ResourceReader(manifestStream);

			IDictionary<string, UnmanagedMemoryStream> ret = new Dictionary<string, UnmanagedMemoryStream>();
			foreach (DictionaryEntry res in reader) {
				string path = (string)res.Key;
				UnmanagedMemoryStream stream = (UnmanagedMemoryStream)res.Value;
				if (Regex.IsMatch(path, filter))
					ret.Add(path, stream);
			}
			return ret;
		}

		/// <summary>
		/// Returns a dictionary of the assembly resources (not embedded).
		/// </summary>
		public static IDictionary<string, UnmanagedMemoryStream> GetResources() {
			return GetResources(".*");
		}

		/// <summary>
		/// Returns a dictionary of the assembly embedded resources.
		/// </summary>
		/// <param name="filter">A regex filter for the resource paths.</param>
		public static IDictionary<string, object> GetEmbeddedResources(string filter) {
			Assembly assembly = Assembly.GetExecutingAssembly();
			string[] resources = assembly.GetManifestResourceNames();

			IDictionary<string, object> ret = new Dictionary<string, object>();
			foreach (string res in resources) {
				if (Regex.IsMatch(res, filter)) {
					Stream stream = assembly.GetManifestResourceStream(res);
					StreamReader sr = new StreamReader(stream);
					ret.Add(res, sr.ReadToEnd());
				}
			}
			return ret;
		}
	}
}
